package com.alander.nexusgo.post.controller;

import com.alander.nexusgo.common.model.dto.PostsListDTO;
import com.alander.nexusgo.common.model.vo.PostsVO;
import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.framework.web.starter.controller.BaseController;
import com.alander.nexusgo.post.model.entity.Posts;
import com.alander.nexusgo.post.service.PostsService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.getPageInfo;
import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.startPage;

/**
* 帖子管理
*/
@RestController
@RequestMapping("/api/posts")
public class PostsController extends BaseController {
    
    @Autowired
    private PostsService postsService;
    
    /**
     * 创建帖子
     */
    @PostMapping
    public Result<PostsVO> create(@RequestBody Posts posts) {
        try {
            PostsVO result = postsService.createPost(posts, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 获取帖子详情
     */
    @GetMapping("/{id}")
    public Result<PostsVO> get(@PathVariable(value = "id") Long id) {
        PostsVO posts = postsService.getPostById(id);
        if (posts == null) {
            return fail("帖子不存在");
        }
        return success(posts);
    }
    
    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public Result<PostsVO> update(@PathVariable(value = "id") Long id, @RequestBody Posts posts) {
        try {
            PostsVO result = postsService.updatePost(id, posts, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable(value = "id") Long id) {
        boolean result = postsService.deletePost(id, getUserId());
        if (result) {
            return success();
        } else {
            return fail("删除失败");
        }
    }
    
    /**
     * 分页查询帖子列表
     */
    @GetMapping
    public PageInfo<PostsVO> list(@RequestBody PostsListDTO postsListDTO) {
        startPage(postsListDTO);
        List<PostsVO> postsVOPage = postsService.listPosts(postsListDTO);
        return getPageInfo(postsVOPage);
    }
}